/**
 * 
 */
package com.detroitchow2;

import java.util.ArrayList;

import com.detroitchow2.api.IArticleUpdateObserver;
import com.detroitchow2.api.IStoreServiceObserver;
import com.detroitchow2.layout.ArticleArrayAdapter;
import com.detroitchow2.util.LogUtil;
import com.detroitchow2.vo.Article;
import com.detroitchow2.vo.StoreVO;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.ViewGroup;

/**
 * @author dave
 *
 */
public class ArticleActivity extends Activity
implements IArticleUpdateObserver, OnClickListener, OnItemClickListener, IStoreServiceObserver
{

  private StoreService storeService;
  private LinearLayout horizontalLinksLayout;
  private ArticleActivity myContext;
  private ListView articlesListView;
  private int storeId;
  private Intent myIntent;
  private StoreVO selectedStore;
  private Button _btnTag;
  private ArrayList<Article> articles;
  private ArticleArrayAdapter articleArrayAdapter;
  /* (non-Javadoc)
   * @see android.app.Activity#onCreate(android.os.Bundle)
   */
  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.article_main);
    if(storeService == null){
      storeService = ((StoreService)getApplicationContext());
      
    }
    horizontalLinksLayout = (LinearLayout)this.findViewById(R.id.layoutTags);
    myContext = this;
    articlesListView = (ListView) this.findViewById(R.id.lvArticles);
    
  }

  /* (non-Javadoc)
   * @see android.app.Activity#onResume()
   */
  @Override
  protected void onResume()
  {
    super.onResume();
    storeId = -1;
    try
    {
      Bundle bundle = getIntent().getExtras();
      storeId = bundle.getInt(StoreService.SELECTED_STORE_KEY);
      
    }catch(Exception e)
    {
      
    }
    
    if(storeId < 1)
      goHome();
    
    selectedStore= storeService.getStore(storeId);
    
    if(selectedStore == null)
    {
      goHome();
    }else 
      processScreen();
  }
  
  private void processScreen()
  {
 // TODO Auto-generated method stub
    horizontalLinksLayout.removeAllViewsInLayout();
    ViewGroup.LayoutParams layoutParams;
    
    String txt = selectedStore.name;
    _btnTag = (Button)getLayoutInflater().inflate(R.layout.linkitem, null);
    _btnTag.setText(txt);
    layoutParams = new ViewGroup.LayoutParams(txt.length() * 25, 75);
    _btnTag.setLayoutParams(layoutParams);
    horizontalLinksLayout.addView(_btnTag);
    
    txt = selectedStore.address + " " + selectedStore.city;
    if(selectedStore.state != null)
      txt += " " + selectedStore.state;
    
    if(selectedStore.zip != null)
      txt += " " + selectedStore.zip;
      
    _btnTag = (Button)getLayoutInflater().inflate(R.layout.linkitem, null);
    _btnTag.setOnClickListener(navButtonClickListener);
    _btnTag.setText(txt);
    layoutParams = new ViewGroup.LayoutParams(txt.length() * 25, 75);
    _btnTag.setLayoutParams(layoutParams);
    horizontalLinksLayout.addView(_btnTag);
    
    if(selectedStore.phone != null) {
      txt = selectedStore.getFormattedPhone();
      _btnTag = (Button)getLayoutInflater().inflate(R.layout.linkitem, null);
      _btnTag.setOnClickListener(phoneButtonClickListener);
      _btnTag.setText(txt);
      layoutParams = new ViewGroup.LayoutParams(txt.length() * 25, 75);
      _btnTag.setLayoutParams(layoutParams);
      horizontalLinksLayout.addView(_btnTag);
    }
      
      
    if(selectedStore.website != null && selectedStore.website.length() > 0) {
      
      txt =selectedStore.website.replaceAll("^http://","");
      _btnTag = (Button)getLayoutInflater().inflate(R.layout.linkitem, null);
      _btnTag.setText(txt);
      layoutParams = new ViewGroup.LayoutParams(txt.length() * 25, 75);
      _btnTag.setOnClickListener(webClickListener);
      _btnTag.setLayoutParams(layoutParams);
      horizontalLinksLayout.addView(_btnTag);
      
    }
    storeService.registerArticleUpdateObserver(this);
    storeService.getArticles(selectedStore.storeId);
    
  }

  private void goHome () 
  {
    myIntent = new Intent(this, MainActivity.class);
    startActivityForResult(myIntent, 0);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    ActionBar actionBar = getActionBar(); // || getActionBar();
    actionBar.setIcon(getResources().getDrawable(R.drawable.action_bar_icon));
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setTitle("");
    menu.add(0, 34343, menu.size(), ""); 
    return true;
    
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) 
  {
    Intent intent;
    
    switch (item.getItemId()) {
        case android.R.id.home:
          intent = new Intent(this, MainActivity.class);
          startActivityForResult(intent, 0);
          return false;
        case R.id.refresh:
          
          //LogUtil.log("onClick", "Click event is btnRefresh");
          intent = new Intent(this, MainActivity.class);
          intent.putExtra(AppIntent.REFRESH, true);
          startActivityForResult(intent, 0);
          return false;
          
        case R.id.search:
          
          intent = new Intent(this, SearchActivity.class);
          startActivityForResult(intent, 0);
          return false;
          
        case R.id.location:
          
          intent = new Intent(this,  MapScreen.class);
          intent.putExtra(AppIntent.MAP_INTENT, AppIntent.LOCATION);
          startActivityForResult(intent, 0);
          return false;
          
        default:
            return super.onOptionsItemSelected(item);
    }
  }
public void onArticleUpdate(ArrayList<Article> _articles) {
    
    storeService.unRegisterArticleUpdateObserver(this);
    // TODO Auto-generated method stub
    articles = _articles;
    if(articles != null) {
      articleArrayAdapter = new ArticleArrayAdapter(this, R.layout.reviewitem, -1, articles);
      if(articleArrayAdapter != null){
        articlesListView.setAdapter(articleArrayAdapter);
        articlesListView.setTextFilterEnabled(true);
        articlesListView.setOnItemClickListener(this);
      }
    }else{
      
      CharSequence text = "No Reviews or articles found for " + selectedStore.name;
      int duration = Toast.LENGTH_SHORT;
      Toast toast = Toast.makeText(this, text, duration);
      toast.show();
    }
  }
  
  //Create an anonymous implementation of OnClickListener
  private OnClickListener phoneButtonClickListener = new OnClickListener() {
      public void onClick(View v) {
        String phone = selectedStore.getPhoneIntentFormat();
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse(phone));
        myContext.startActivity(intent);
      }
  };
  
  
  
  //Create an anonymous implementation of OnClickListener
  private OnClickListener webClickListener = new OnClickListener() {
      public void onClick(View v) {
        String url = selectedStore.website;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        myContext.startActivity(intent);
      }
  };  
  
  
//Create an anonymous implementation of OnClickListener
  private OnClickListener navButtonClickListener = new OnClickListener() 
  {
      public void onClick(View v) 
      {
        
        if(selectedStore.address != null) 
        {
          String addressLine = selectedStore.address;
          if(selectedStore.city != null)
            addressLine += "+" + selectedStore.city;
          
          if(selectedStore.state != null)
            addressLine += "+" + selectedStore.state;
          
          if(selectedStore.zip != null)
            addressLine += "+" + selectedStore.zip;
          
          addressLine = addressLine.replaceAll(" ", "+");
          LogUtil.log("navButtonClickListener", addressLine);
          /*
          intent = new Intent(android.content.Intent.ACTION_VIEW, 
          Uri.parse("google.navigation:q=" + addressLine));
          */
          Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
          Uri.parse("http://maps.google.com/maps?daddr=" + addressLine));
          myContext.startActivity(intent);
          
        }
      }
  };

  @Override
  public void onStoreManagerUpdate()
  {
    // TODO Auto-generated method stub
    
  }

  @Override
  public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3)
  {
    String url =  articles.get(index).articleUrl ;
    // get the intent
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    myContext.startActivity(intent);
    
  }

  @Override
  public void onClick(View v)
  {
    // TODO Auto-generated method stub
    
  }
  
}

 